<template>
  <el-dialog
    :title="'新增'+p_name_en+'的子权限'"
    :visible="dialogVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    center
  >
    <el-form
      ref="addEditForm"
      v-loading="isLoading > 0"
      :model="formData"
      :rules="rules"
      label-width="100px"
      class="add-edit-form"
    >
      <el-form-item label="权限名" prop="name_cn">
        <el-input v-model="formData.name_cn" />
      </el-form-item>
      <el-form-item label="key(必须是英文)" prop="name_en">
        <el-input v-model="formData.name_en" />
      </el-form-item>

      <el-form-item label="是否上线">
        <el-switch
          :value="formData.status === 1"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="formData.status = formData.status === 1 ? -1 : 1"
        />
      </el-form-item>

      <el-form-item class="submit-box">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import lodash from 'lodash'
import { addOneAdminAuth, updateOneAdminAuth } from '@/api/admin_auth'
let formData = null
export default {
  name: 'AddEdit',
  components: {},
  props: {},
  data() {
    return {
      dialogVisible: false,
      isLoading: 0,
      p_name_en: '',
      formData: {},
      rules: {
        name_cn: [
          { required: true, message: '不能为空', trigger: ['change', 'blur'] }
        ],
        name_en: [
          { required: true, message: '不能为空', trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created() {
  },
  mounted() {},
  methods: {
    handleClose() {
      this.dialogVisible = false
    },
    open(row) {
      this.dialogVisible = true
      formData = {
        p_id: row.id,
        name_cn: undefined,
        name_en: undefined,
        status: -1
      }
      this.p_name_en = row.name_en
      this.resetForm()
    },
    resetForm() {
      this.formData = lodash.cloneDeep(formData)
      this.$nextTick(() => {
        this.$refs.addEditForm.clearValidate()
      })
    },
    submitForm() {
      if (this.isLoading > 0) return
      this.$refs.addEditForm.validate(async vaild => {
        if (!vaild) return
        try {
          this.isLoading++
          if (this.formData.id) {
            await updateOneAdminAuth(this.formData)
          } else {
            await addOneAdminAuth(this.formData)
          }
          this.$emit('refresh')
          this.handleClose()
        } finally {
          this.isLoading--
        }
      })
    }

  }
}
</script>

<style lang="scss" scoped>
.submit-box {
  display: flex;
  justify-content: flex-end;
}
</style>
